package com.abc.robot01.room

import android.content.Context
import android.util.Log
import androidx.annotation.VisibleForTesting
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.abc.robot01.RobotOSApplication
import com.abc.robot01.room.bean.ChatAnswerBean
import com.abc.robot01.room.bean.ChatCount
import com.abc.robot01.room.bean.ChatQuestionBean
import com.abc.robot01.room.bean.CmdBean
import com.abc.robot01.room.bean.SystemMessageBean
import com.abc.robot01.room.dao.ChatAnswerDao
import com.abc.robot01.room.dao.ChatCountDao
import com.abc.robot01.room.dao.ChatQuestionDao
import com.abc.robot01.room.dao.CmdDao
import com.abc.robot01.room.dao.SystemMessageDao

@Database(
    entities = [ChatQuestionBean::class, ChatAnswerBean::class, ChatCount::class,SystemMessageBean::class,CmdBean::class],
    version = 2,
    exportSchema = false
)
@TypeConverters(DateConverter::class)
abstract class AppDatabase : RoomDatabase() {
    abstract fun chatQuestionDao(): ChatQuestionDao
    abstract fun chatAnswerDao(): ChatAnswerDao
    abstract fun chatCountDao(): ChatCountDao
    abstract fun systemMessageDao(): SystemMessageDao
    abstract fun cmdDao(): CmdDao

    private val mIsDatabaseCreated = MutableLiveData<Boolean>()

    /**
     * Check whether the database already exists and expose it via [.getDatabaseCreated]
     */
    private fun updateDatabaseCreated(context: Context) {
        if (context.getDatabasePath(DATABASE_NAME).exists()) {
            setDatabaseCreated()
        }
    }

    private fun setDatabaseCreated() {
        mIsDatabaseCreated.postValue(true)
    }

    val databaseCreated: LiveData<Boolean>
        get() = mIsDatabaseCreated


    companion object {
        private var sInstance: AppDatabase? = null

        @VisibleForTesting
        val DATABASE_NAME = "basic-sample-db"

        /*fun getInstance(context: Context, executors: AppExecutors): AppDatabase? {
            if (sInstance == null) {
                synchronized(AppDatabase::class.java) {
                    if (sInstance == null) {
                        Log.e("AppDatabase", "getInstance -- executors= $executors")
                        sInstance = buildDatabase(context.applicationContext, executors)
                        sInstance!!.updateDatabaseCreated(context.applicationContext)
                    }

                }
            }
            return sInstance
        }
*/



        /**
         * Build the database. [Builder.build] only sets up the database configuration and
         * creates a new instance of the database.
         * The SQLite database is only created when it's accessed for the first time.
         */
        /*private fun buildDatabase(
            appContext: Context,
            executors: AppExecutors
        ): AppDatabase {

            Log.e("AppDatabase", "buildDatabase 111}")
            val appDatabaseBuilder =
                databaseBuilder(appContext, AppDatabase::class.java, DATABASE_NAME)

            Log.e("AppDatabase", "buildDatabase 222}")

            appDatabaseBuilder.addCallback(object : Callback() {
                override fun onCreate(db: SupportSQLiteDatabase) {
                    super.onCreate(db)
                    Log.e("AppDatabase", "onCreate}")
                    executors.diskIO().execute {

                        Log.e("AppDatabase", "diskIo")
                        // Add a delay to simulate a long-running operation
                        // Generate the data for pre-population
                        val database = getInstance(appContext, executors)
                        val products = DataGenerator.generateProducts()
                        insertData(database, products)
                        // notify that the database was created and it's ready to be used
                        database!!.setDatabaseCreated()



                    }
                }
            })
                    appDatabaseBuilder.addMigrations(MIGRATION_1_2);
            return appDatabaseBuilder
                .build()
        }*/

        private val MIGRATION_1_2 = Migration(1, 2) {
            fun migrate(database: SupportSQLiteDatabase) {
//                database.execSQL("CREATE VIRTUAL TABLE IF NOT EXISTS `productsFts` USING FTS4("
//                        + "`name` TEXT, `description` TEXT, content=`products`)");
//                database.execSQL("INSERT INTO productsFts (`rowid`, `name`, `description`) "
//                        + "SELECT `id`, `name`, `description` FROM products");

            }
        };
    }
}

object DatabaseContext {
    lateinit var application: Context

    private val database by lazy {
        application = RobotOSApplication.getInstance()
        Room.databaseBuilder(application, AppDatabase::class.java, "basic-sample-db")
            .addCallback(object : RoomDatabase.Callback() {
                override fun onCreate(db: SupportSQLiteDatabase) {
                    super.onCreate(db)
                    Log.e("AppDatabase", "databaseBuilder --> onCreate:")
                    AppExecutors().diskIO().execute {
                    }
                }

            })
            .allowMainThreadQueries()
            .build()
    }

    fun getChatQuestionDao() = database.chatQuestionDao().also {
        Log.e("AppDatabase", "chatQuestionDao -----")
    }

    fun getChatAnswerDao() = database.chatAnswerDao().also {
        Log.e("AppDatabase", "chatAnswerDao -----")
    }

    fun getCmdDao() = database.cmdDao().also {
        Log.e("AppDatabase", "chatAnswerDao -----")
    }
}
